package com.microservice.auth.controller;

import com.microservice.api.common.Result;

import com.microservice.api.user.dto.LoginResponseDTO;
import com.microservice.api.user.dto.UserLoginDTO;
import com.microservice.auth.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 认证控制器
 */
@Slf4j
@RestController
@RequestMapping("/auth")
public class AuthController {
    
    @Autowired
    private AuthService authService;
    
    /**
     * 健康检查
     */
    @GetMapping("/health")
    public String health() {
        return "Auth Service is running";
    }
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<LoginResponseDTO> login(@RequestBody UserLoginDTO loginDTO) {
        log.info("用户登录请求: {}", loginDTO.getUsername());
        try {
            LoginResponseDTO response = authService.login(loginDTO);
            return Result.success("登录成功", response);
        } catch (Exception e) {
            log.error("登录失败", e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 刷新令牌
     */
    @PostMapping("/refresh")
    public Result<LoginResponseDTO> refreshToken(@RequestHeader("Refresh-Token") String refreshToken) {
        log.info("刷新令牌请求");
        try {
            LoginResponseDTO response = authService.refreshToken(refreshToken);
            return Result.success("刷新成功", response);
        } catch (Exception e) {
            log.error("刷新令牌失败", e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 验证令牌
     */
    @GetMapping("/validate")
    public Result<Boolean> validateToken(@RequestHeader("Authorization") String token) {
        try {
            // 移除 "Bearer " 前缀
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            boolean valid = authService.validateToken(token);
            return Result.success(valid);
        } catch (Exception e) {
            log.error("验证令牌失败", e);
            return Result.success(false);
        }
    }
    
    /**
     * 用户登出
     */
    @PostMapping("/logout")
    public Result<Void> logout(@RequestHeader("Authorization") String token) {
        log.info("用户登出请求");
        try {
            // 移除 "Bearer " 前缀
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            authService.logout(token);
            return Result.success("登出成功", null);
        } catch (Exception e) {
            log.error("登出失败", e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 从Token中解析用户ID
     */
    @GetMapping("/parse/userId")
    public Result<Long> getUserIdFromToken(@RequestHeader("Authorization") String token) {
        try {
            // 移除 "Bearer " 前缀
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            Long userId = authService.getUserIdFromToken(token);
            return Result.success(userId);
        } catch (Exception e) {
            log.error("解析用户ID失败", e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 从Token中解析用户名
     */
    @GetMapping("/parse/username")
    public Result<String> getUsernameFromToken(@RequestHeader("Authorization") String token) {
        try {
            // 移除 "Bearer " 前缀
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            String username = authService.getUsernameFromToken(token);
            return Result.success(username);
        } catch (Exception e) {
            log.error("解析用户名失败", e);
            return Result.error(e.getMessage());
        }
    }

    @GetMapping("/parse/nickname")
    Result<String> getNicknameFromToken(@RequestHeader("Authorization") String token){

        try {
            // 移除 "Bearer " 前缀
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            String nickname = authService.getNicknameFromToken(token);
            return Result.success(nickname);
        } catch (Exception e) {
            log.error("解析用户名失败", e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 使指定用户的所有Token失效
     * 用于封禁用户、强制登出等场景
     */
    @GetMapping("/invalidate/user/{userId}")
    public Result<String> invalidateUserTokens(@PathVariable("userId") Long userId) {
        log.info("使用户 {} 的所有Token失效", userId);
        try {
            authService.invalidateUserTokens(userId);
            return Result.success("用户Token已全部失效");
        } catch (Exception e) {
            log.error("使用户Token失效失败", e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 解除用户Token封禁
     * 用于解封用户账号
     */
    @PostMapping("/unblock/user/{userId}")
    public Result<String> unblockUserTokens(@PathVariable("userId") Long userId) {
        log.info("解除用户 {} 的Token封禁", userId);
        try {
            authService.unblockUserTokens(userId);
            return Result.success("用户Token封禁已解除");
        } catch (Exception e) {
            log.error("解除用户Token封禁失败", e);
            return Result.error(e.getMessage());
        }
    }
}
